package com.cskaoyan.service;

import com.cskaoyan.bean.bo.order.OrderListBO;
import com.cskaoyan.bean.reverseengineering.*;
import com.cskaoyan.bean.vo.order.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.wx.bean.bo.aftersalebo.AftersaleBO;

import com.cskaoyan.mapper.MarketExpressMapper;
import com.cskaoyan.mapper.MarketOrderGoodsMapper;
import com.cskaoyan.mapper.MarketOrderMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.wx.bean.bo.orderbo.WxOrderListBO;
import com.cskaoyan.wx.bean.bo.orderbo.WxOrderSubmitBO;
import com.cskaoyan.wx.bean.po.orderpo.*;
import com.cskaoyan.wx.bean.vo.WxUserIndexOrderVO;
import com.cskaoyan.wx.bean.vo.WxUserIndexVO;
import com.cskaoyan.wx.bean.vo.aftersale.WxAfterSaleDetail;
import com.cskaoyan.wx.bean.vo.ordervo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.*;

/**
 * 
 * @since 2022/05/05 23:19
 * @author tangwei
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketAftersaleMapper marketAftersaleMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketExpressMapper marketExpressMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;


    @Override
    public OrderListVO queryAllOrders(OrderListBO orderListBO) {
        // Integer hasDeleted = 0;
        //
        // Integer page = orderListBO.getPage();
        // Integer limit =orderListBO.getLimit();
        // String sort = orderListBO.getSort();
        // String order = orderListBO.getOrder();
        // PageHelper.startPage(page, limit);
        //
        // List<WxOrderListVO> orderListVOList = marketOrderMapper.selectAllOrders(sort, order, hasDeleted, orderListBO);
        //
        // return orderListVOList;

        Integer page = orderListBO.getPage();
        Integer limit =orderListBO.getLimit();
        String sort = orderListBO.getSort();
        String order = orderListBO.getOrder();

        PageHelper.startPage(page, limit);

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.setOrderByClause(sort + " " + order);

        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();

        if (!(orderListBO.getOrderStatusArray() == null)) {
            criteria.andOrderStatusIn(Arrays.asList(orderListBO.getOrderStatusArray()));
        }
        if (!(orderListBO.getUserId() == null)) {
            criteria.andUserIdEqualTo(orderListBO.getUserId());
        }
        if (!(orderListBO.getOrderSn() == null)) {
            criteria.andOrderSnLike("%" + orderListBO.getOrderSn() + "%");
        }
        if ((orderListBO.getStart() != null) || (orderListBO.getEnd()) != null) {
            criteria.andPayTimeBetween(orderListBO.getStart(), orderListBO.getEnd());
        }
        criteria.andDeletedEqualTo(false);
        List<MarketOrder> orders = marketOrderMapper.selectByExample(marketOrderExample);

        PageInfo<MarketOrder> pageInfo = new PageInfo<>(orders);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        return OrderListVO.data(total, pages, limit, page, orders);
    }

    @Override
    public List<ExpressListVO> queryAllExpress() {
        // MarketOrderExample marketOrderExample = new MarketOrderExample();
        // MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        //
        // criteria.andShipSnIsNotNull();
        // List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        //
        // ArrayList<ExpressListVO> expressListVOS = new ArrayList<>();
        //
        // for (int i = 0; i < marketOrders.size(); i++) {
        //     ExpressListVO expressListVO = new ExpressListVO();
        //     expressListVO.setCode(marketOrders.get(i).getShipSn());
        //     expressListVO.setName(marketOrders.get(i).getShipChannel());
        //     expressListVOS.add(expressListVO);
        // }
        //
        // return expressListVOS;

        List<ExpressListVO> expressListVOList = marketOrderMapper.selectAllExpress();
        return expressListVOList;
    }

    @Override
    public boolean deleteOneOrder(Map orderId) {
        Integer deletedOrderId = (Integer) orderId.get("orderId");

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(deletedOrderId);
        marketOrder.setUpdateTime(new Date());

        MarketOrder marketOrderDelete = marketOrderMapper.selectByPrimaryKey(deletedOrderId);
        Short orderStatus = marketOrderDelete.getOrderStatus();
        if (orderStatus == 101 || orderStatus == 102 || orderStatus == 103) {
            marketOrder.setDeleted(true);
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
            return true;
        }
        return false;
    }

    @Override
    public OrderDetailVO queryOrderInfoBy(Integer id) {
        // 获得订单基本信息
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(id);

        OrderDetailOrderVO orderDetailOrderVO = new OrderDetailOrderVO();
        orderDetailOrderVO.setId(marketOrder.getId());
        orderDetailOrderVO.setUserId(marketOrder.getUserId());
        orderDetailOrderVO.setOrderSn(marketOrder.getOrderSn());
        orderDetailOrderVO.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderDetailOrderVO.setConsignee(marketOrder.getConsignee());
        orderDetailOrderVO.setMobile(marketOrder.getMobile());
        orderDetailOrderVO.setAddress(marketOrder.getAddress());
        orderDetailOrderVO.setMessage(marketOrder.getMessage());
        orderDetailOrderVO.setGoodsPrice(marketOrder.getGoodsPrice());
        orderDetailOrderVO.setFreightPrice(marketOrder.getFreightPrice());
        orderDetailOrderVO.setCouponPrice(marketOrder.getCouponPrice());
        orderDetailOrderVO.setIntegralPrice(marketOrder.getIntegralPrice());
        orderDetailOrderVO.setGoodsPrice(marketOrder.getGoodsPrice());
        orderDetailOrderVO.setOrderPrice(marketOrder.getOrderPrice());
        orderDetailOrderVO.setActualPrice(marketOrder.getActualPrice());
        orderDetailOrderVO.setComments(marketOrder.getComments());
        orderDetailOrderVO.setEndTime(marketOrder.getEndTime());
        orderDetailOrderVO.setAddTime(marketOrder.getAddTime());
        orderDetailOrderVO.setUpdateTime(marketOrder.getUpdateTime());
        orderDetailOrderVO.setDeleted(marketOrder.getDeleted());
        orderDetailOrderVO.setOrderStatus(marketOrder.getOrderStatus());
        orderDetailOrderVO.setGrouponPrice(marketOrder.getGrouponPrice());

        // 获得订单包含的商品的信息
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(id);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);



        // 获得订单的用户信息
        Integer userId = marketOrder.getUserId();
        MarketUser marketUser = marketUserMapper.selectByPrimaryKey(userId);

        OrderDetailUserVO orderDetailUserVO = new OrderDetailUserVO();
        orderDetailUserVO.setNickname(marketUser.getNickname());
        orderDetailUserVO.setAvatar(marketUser.getAvatar());

        return new OrderDetailVO(orderDetailOrderVO, marketOrderGoods, orderDetailUserVO);
    }

    @Override
    public void shipOrder(Map orderShip) {
        MarketOrder marketOrder = new MarketOrder();

        marketOrder.setId((Integer) orderShip.get("orderId"));
        marketOrder.setShipChannel((String) orderShip.get("shipChannel"));
        marketOrder.setShipSn((String) orderShip.get("shipSn"));

        // 修改订单状态为已发货
        marketOrder.setOrderStatus((short) 301);

        Date date = new Date();
        marketOrder.setShipTime(date);
        marketOrder.setUpdateTime(date);

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

        // Integer orderId = (Integer) orderShip.get("orderId");
        //
        // MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        // MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        // MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        //
        // criteria.andOrderIdEqualTo(orderId);
        //
        // marketOrderGoods.setComment(0);
        //
        // marketOrderGoodsMapper.updateByExampleSelective(marketOrderGoods, marketOrderGoodsExample);

    }

    @Override
    public void refundOrder(Map orderRefund) {
        MarketOrder marketOrder = new MarketOrder();

        marketOrder.setId((Integer) orderRefund.get("orderId"));
        // marketOrder.setRefundAmount((BigDecimal) orderRefund.get("refundMoney"));
        marketOrder.setRefundAmount(new BigDecimal((Integer) orderRefund.get("refundMoney")));

        // 修改订单状态为已退款
        marketOrder.setOrderStatus((short) 203);

        Date date = new Date();
        marketOrder.setRefundTime(date);
        marketOrder.setUpdateTime(date);

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public WxOrderVO list(WxOrderListBO orderListBO,String username) {

        // user_id
        Integer userId = marketUserMapper.selectByusername(username);


        MarketOrderExample example = new MarketOrderExample();
        // MarketOrderExample.Criteria criteria = example.createCriteria();
        MarketOrderExample.Criteria criteria = example.createCriteria();
        MarketOrderExample.Criteria criteria2 = example.createCriteria();
        // 根据showType进行订单状态的分类
        Integer showType = orderListBO.getShowType();

        // 未付款
        if (showType == 1) {
            criteria.andOrderStatusEqualTo(((short) 101));
        }
        // 待发货
        if (showType == 2) {
            criteria.andOrderStatusEqualTo(((short) 201));
        }
        // 待收货
        if (showType == 3) {
            criteria.andOrderStatusEqualTo(((short) 301));
        }
        // 待评价
        if (showType == 4) {
            criteria.andOrderStatusEqualTo(((short) 401));
            criteria.andCommentsNotEqualTo((((short) 0)));
            criteria2.andOrderStatusEqualTo(((short) 402));
            criteria2.andUserIdEqualTo(userId);
            criteria2.andDeletedEqualTo(false);
            criteria2.andCommentsNotEqualTo((((short) 0)));
            example.or(criteria2);
        }
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        // 排序
        example.setOrderByClause("id DESC");
        List<MarketOrder> marketOrderList = marketOrderMapper.selectByExample(example);

        List<WxOrderListVO> wxOrderListVOList = new ArrayList<>();

        // 对list赋值
        for (MarketOrder marketOrder : marketOrderList) {

            // 对订单表赋值
            WxOrderListVO wxOrderListVO = new WxOrderListVO();
            wxOrderListVO.setActualPrice(marketOrder.getActualPrice());
            wxOrderListVO.setAftersaleStatus(marketOrder.getAftersaleStatus());
            wxOrderListVO.setId(marketOrder.getId());
            wxOrderListVO.setOrderSn(marketOrder.getOrderSn());
            String orderStatusText = HandleOptionUtils.orderStatus(((int) marketOrder.getOrderStatus()));
            wxOrderListVO.setOrderStatusText(orderStatusText);

            // 根据订单id 查询goodslist表
            // List<WxOrderGoodslistVO> orderGoodslist = new ArrayList<>();
            List<WxOrderDetailOrderGoodsVO> goodslist = marketOrderGoodsMapper.selectByPrimaryKey2(marketOrder.getId());
            // WxOrderGoodslistVO goodslist = marketOrderGoodsMapper.selectById();
            // orderGoodslist.add(goodslist);
            wxOrderListVO.setGoodsList(goodslist);


            // handleOption
            Short orderStatus = marketOrder.getOrderStatus();
            HandleOption handleOption = HandleOptionUtils.hanle(((int) orderStatus));
            wxOrderListVO.setHandleOption(handleOption);


            wxOrderListVOList.add(wxOrderListVO);


        }

        // 得到全部订单 赋值OrderVO的list
        WxOrderVO wxOrderVO = new WxOrderVO();

        // 分页
        PageInfo<WxOrderListVO> pageInfo = new PageInfo<>(wxOrderListVOList);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        wxOrderVO.setList(wxOrderListVOList);
        wxOrderVO.setLimit(orderListBO.getLimit());
        wxOrderVO.setPage(orderListBO.getPage());
        wxOrderVO.setPages(pages);
        wxOrderVO.setTotal((int) total);

        return wxOrderVO;
    }

    @Override
    public WxOrderDetailVO detail(Integer orderId) {

        // 对orderInfo赋值
        WxOrderDetailOrderInfoVO orderInfo = marketOrderMapper.selectByPrimaryKey2(orderId);
        orderInfo.setHandleOption(HandleOptionUtils.hanle((int) orderInfo.getOrderStatus()));
        orderInfo.setOrderStatusText(HandleOptionUtils.orderStatus((int)orderInfo.getOrderStatus()));
        String expCode = orderInfo.getExpCode();
        String expName = marketOrderMapper.selectExpNameByexpCode(expCode);
        orderInfo.setExpName(expName);


        // 对orderGoods赋值
        List<WxOrderDetailOrderGoodsVO> orderGoods = marketOrderGoodsMapper.selectByPrimaryKey2(orderInfo.getId());

        // 对快递赋值
        List<WxOrderDetailExpressInfoVO> expressInfo = new ArrayList<>();

        // 对data赋值 并返回
        WxOrderDetailVO data = new WxOrderDetailVO();
        data.setExpressInfo(expressInfo);
        data.setOrderGoods(orderGoods);
        data.setOrderInfo(orderInfo);

        return data;
    }

    @Override
    public void cancel(Integer orderId) {
        WxMarketOrder marketOrder =marketOrderMapper.selectByPrimaryKey3(orderId);
        // 如果超过半小时未支付，则由系统取消
        // Date dateNow = new Date();

        // 按照addtime来判断是否超过半小时

        // Long time = (dateNow.getTime() - marketOrder.getAddTime().getTime()) / 1000 / 60;
        //
        // if (time >= 30) {
        //     // 如果超过半小时，则由系统取消订单
        // }
        marketOrder.setOrderStatus(((short) 102));
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey2(marketOrder);
    }

    @Override
    public void delete(Integer orderId) {
        WxMarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey3(orderId);
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKey2(marketOrder);
    }

    @Override
    public void refund(int orderId) {
        WxMarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey3(orderId);
        marketOrder.setOrderStatus(((short) 202));
        marketOrder.setAftersaleStatus(((short) 1));
        marketOrder.setUpdateTime(new Date());
        // 退款时间
        marketOrder.setRefundTime(new Date());

        marketOrderMapper.updateByPrimaryKey2(marketOrder);
    }

    @Override
    public void confirm(int orderId) {
        WxMarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey3(orderId);

        // 遍历market_order_goods表 设置comments
        List<WxOrderDetailOrderGoodsVO> goodsList = marketOrderGoodsMapper.selectByPrimaryKey2(orderId);
        int size = goodsList.size();

        marketOrder.setOrderStatus(((short) 401));
        marketOrder.setConfirmTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrder.setComments(((short) size));

        marketOrderMapper.updateByPrimaryKey2(marketOrder);
    }

    @Override
    public void prepay(int orderId) {
        WxMarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey3(orderId);
        marketOrder.setOrderStatus(((short) 201));
        marketOrder.setPayId(TimeUtils.timeTrans(new Date()));
        marketOrder.setPayTime(new Date());
        // marketOrder.setUpdateTime(new Date());

        marketOrderMapper.updateByPrimaryKey2(marketOrder);

    }

    @Override
    public void aftersaleSubmit(AftersaleBO aftersaleBO) {
        WxMarketOrder wxMarketOrder = marketOrderMapper.selectByPrimaryKey3(Integer.parseInt(aftersaleBO.getOrderId()));

        wxMarketOrder.setRefundAmount(aftersaleBO.getAmount());
        wxMarketOrder.setRefundContent(aftersaleBO.getReason());
        wxMarketOrder.setRefundType(aftersaleBO.getTypeDesc());
        wxMarketOrder.setAftersaleStatus(((short) 1));
        wxMarketOrder.setRefundTime(new Date());
        wxMarketOrder.setUpdateTime(new Date());
        // 修改market order表格
        marketOrderMapper.updateByPrimaryKey2(wxMarketOrder);

        // 新增market aftersale表格的数据
        // List<String> pictures = aftersaleBO.getPictures();
        // String pictureString = pictures.toString();
        MarketAftersale marketAftersale = new MarketAftersale();
        // 赋值订单编号
        marketAftersale.setOrderId(aftersaleBO.getOrderId());
        // 赋值售后类型type
        marketAftersale.setType(aftersaleBO.getType());
        // 赋值退款原因
        marketAftersale.setReason(aftersaleBO.getReason());
        // 赋值退款金额
        marketAftersale.setAmount(aftersaleBO.getAmount());
        // 赋值退款说明
        marketAftersale.setComment(aftersaleBO.getTypeDesc());
        // 售后订单编号eg：20220509 003506
        marketAftersale.setAftersaleSn(TimeUtils.timeTrans(new Date()));
        // 赋值userId
        marketAftersale.setUserId(wxMarketOrder.getUserId());
        // 设置订单状态 1---> 用户已申请
        marketAftersale.setStatus(((short) 1));
        // 设置添加时间
        marketAftersale.setAddTime(new Date());
        // 设置更新时间
        marketAftersale.setUpdateTime(new Date());
        // 设置图片
        marketAftersale.setPictures(aftersaleBO.getPictures());

        marketAftersaleMapper.insert(marketAftersale);
    }

    @Override
    public WxAfterSaleDetail aftersaleDetail(Integer orderId) {

        // order表
        WxMarketOrder order = marketOrderMapper.selectByPrimaryKey3(orderId);

        // orderGoods表
        List<WxOrderDetailOrderGoodsVO> orderGoods = marketOrderGoodsMapper.selectByPrimaryKey2(orderId);

        // aftersale表 通过售后表的id查询
        MarketAftersale aftersale = marketAftersaleMapper.selectByPrimaryKey2(orderId);

        WxAfterSaleDetail data = new WxAfterSaleDetail();
        data.setAftersale(aftersale);
        data.setOrder(order);
        data.setOrderGoods(orderGoods);

        return data;
    }

    @Override
    public WxOrderDetailOrderGoodsVO goods(Integer orderId, Integer goodsId) {

        WxOrderDetailOrderGoodsVO wxOrderDetailOrderGoodsVOS = marketOrderGoodsMapper.selectByPrimaryKey3(orderId,goodsId);

        return wxOrderDetailOrderGoodsVOS;
    }

    @Override
    public void comment(WxComment wxComment) {

        MarketComment marketComment = new MarketComment();

        Integer orderGoodsId = wxComment.getOrderGoodsId();
        // 通过ordersGoodsId查出goodsId，赋值valueId
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);
        Integer goodsId = marketOrderGoods.getGoodsId();
        // 通过ordersGoodsId查出orderId
        Integer orderId = marketOrderGoods.getOrderId();
        // 通过orderId查出userId
        WxMarketOrder wxMarketOrder = marketOrderMapper.selectByPrimaryKey3(orderId);
        Integer userId = wxMarketOrder.getUserId();

        marketComment.setValueId(goodsId);
        marketComment.setType(((byte) 0));
        marketComment.setUserId(userId);
        if (wxComment.getPicUrls() != null) {
            marketComment.setHasPicture(true);
        } else {
            marketComment.setHasPicture(false);
        }
        marketComment.setStar(wxComment.getStar());
        marketComment.setAddTime(new Date());
        marketComment.setUpdateTime(new Date());
        marketComment.setPicUrls(wxComment.getPicUrls());
        marketComment.setContent(wxComment.getContent());

        marketCommentMapper.insertSelective(marketComment);

        // 修改orderGoods表
        marketOrderGoods.setUpdateTime(new Date());
        marketOrderGoods.setComment(marketComment.getId());
        marketOrderGoodsMapper.updateByPrimaryKey(marketOrderGoods);


        // 修改order表
        wxMarketOrder.setUpdateTime(new Date());
        wxMarketOrder.setEndTime(new Date());
        Short comments = wxMarketOrder.getComments();
        // 未回复评论数减一
        int commentsNew = comments - 1;
        wxMarketOrder.setComments(((short) commentsNew));
        marketOrderMapper.updateByPrimaryKey2(wxMarketOrder);


    }

    @Override
    public int reply(Map comment) {
        Integer id = (Integer) comment.get("commentId");
        MarketComment queryContent = marketCommentMapper.selectByPrimaryKey(id);
        System.out.println(queryContent.getAdminContent());
        if (!"".equals(queryContent.getAdminContent())) {
            return 622;
        }
        MarketComment marketComment = new MarketComment();
        marketComment.setId(id);
        String content = (String) comment.get("content");
        marketComment.setAdminContent(content);
        marketComment.setUpdateTime(new Date());
        marketCommentMapper.updateByPrimaryKeySelective(marketComment);
        return 200;
    }

    @Override
    public WxOrderSubmitVO submit(WxOrderSubmitBO wxOrderSubmitBO,String username) {

        // 思路：
        // 新增market order表的记录

        // user_id
        Integer userId = marketUserMapper.selectByusername(username);

        // WxMarketOrder
        WxMarketOrder wxMarketOrder = new WxMarketOrder();
        wxMarketOrder.setUserId(userId);
        wxMarketOrder.setOrderSn(TimeUtils.timeTrans(new Date()));
        wxMarketOrder.setOrderStatus(((short) 101));

        // 查询marketAddress表
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderSubmitBO.getAddressId());
        wxMarketOrder.setConsignee(marketAddress.getName());
        wxMarketOrder.setMobile(marketAddress.getTel());
        wxMarketOrder.setAddress(marketAddress.getProvince() + marketAddress.getCity() + marketAddress.getCounty()
        + marketAddress.getAddressDetail());
        wxMarketOrder.setMessage(wxOrderSubmitBO.getMessage());


        // cartId为0时，代表从购物车里选择check=1的商品
        if (wxOrderSubmitBO.getCartId() == 0) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andCheckedEqualTo(true);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
            // 循环遍历marketCarts 得到总价格
            int goodsPriceTotal2 = 0;
            int number = 0;
            for (MarketCart marketCart : marketCarts) {
                BigDecimal multiply = marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber()));
                int goodsPrice = multiply.intValue();
                goodsPriceTotal2 += goodsPrice;
                // 设置购物车cart状态
                marketCart.setDeleted(true);
                marketCart.setChecked(false);
                marketCartMapper.updateByPrimaryKey(marketCart);
                // 得到待评价商品数量
                number ++;
            }
            BigDecimal goodsPriceTotal = BigDecimal.valueOf(goodsPriceTotal2);
            // 商品价格
            wxMarketOrder.setGoodsPrice(goodsPriceTotal);

            // 运输费用
            if (goodsPriceTotal.intValue() >= 88) {
                wxMarketOrder.setFreightPrice(BigDecimal.valueOf(0));
            } else {
                wxMarketOrder.setFreightPrice(BigDecimal.valueOf(10));
            }

            // 优惠券减免  -1代表不使用优惠券
            if (wxOrderSubmitBO.getCouponId() < 0) {
                // 不使用优惠券
                // wxMarketOrder.setFreightPrice(BigDecimal.valueOf(0));
                wxMarketOrder.setCouponPrice(BigDecimal.valueOf(0));
            } else if (wxOrderSubmitBO.getCouponId() > 0) {
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmitBO.getCouponId());
                // 满足使用条件
                wxMarketOrder.setCouponPrice(marketCoupon.getDiscount());
            } else {
                // 默认使用金额最大的优惠券
                // 若couponId为0，查询该用户所有可用优惠券,找到面额最大的优惠券使用
                MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
                marketCouponUserExample.createCriteria()
                        .andUserIdEqualTo(userId);
                List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
                // 遍历查询优惠券使用状态，如果没有使用，则选择优惠券金额最大的一张
                int discountMax = 0;
                for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                    // 判断是否使用
                    if (marketCouponUser.getStatus() == 0) {
                        Integer couponId = marketCouponUser.getCouponId();
                        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
                        // 选择优惠券金额最大的一张，需要判断条件
                        if (goodsPriceTotal.intValue() > marketCoupon.getMin().intValue()) {
                            // 如果满足了最低金额，则代表可以使用优惠券
                            if (marketCoupon.getDiscount().intValue() >= discountMax ) {
                                discountMax = marketCoupon.getDiscount().intValue();
                            }
                        }
                    }
                }
                wxMarketOrder.setCouponPrice(BigDecimal.valueOf(discountMax));
            }

            // 订单费用
            double orderPrice = wxMarketOrder.getGoodsPrice().doubleValue() + wxMarketOrder.getFreightPrice().doubleValue() - wxMarketOrder.getCouponPrice().doubleValue();

            wxMarketOrder.setOrderPrice(BigDecimal.valueOf(orderPrice));

            wxMarketOrder.setActualPrice(BigDecimal.valueOf(orderPrice));

            wxMarketOrder.setAddTime(new Date());
            wxMarketOrder.setUpdateTime(new Date());
            wxMarketOrder.setIntegralPrice(BigDecimal.valueOf(0));
            wxMarketOrder.setGrouponPrice(BigDecimal.valueOf(0));
            // wxMarketOrder.setComments(((short) number));
            marketOrderMapper.insert2(wxMarketOrder);

            // 新增market order goods表的记录
            for (MarketCart marketCart : marketCarts) {
                WxMarketOrderGoods wxMarketOrderGoods = new WxMarketOrderGoods();
                wxMarketOrderGoods.setOrderId(wxMarketOrder.getId());
                wxMarketOrderGoods.setGoodsId(marketCart.getGoodsId());
                wxMarketOrderGoods.setGoodsName(marketCart.getGoodsName());
                wxMarketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
                wxMarketOrderGoods.setProductId(marketCart.getProductId());
                wxMarketOrderGoods.setPrice(marketCart.getPrice());
                wxMarketOrderGoods.setNumber(marketCart.getNumber().shortValue());
                wxMarketOrderGoods.setSpecifications(marketCart.getSpecifications());
                wxMarketOrderGoods.setPicUrl(marketCart.getPicUrl());
                wxMarketOrderGoods.setAddTime(new Date());
                wxMarketOrderGoods.setUpdateTime(new Date());
                // wxMarketOrderGoods.setComment(-2);
                marketOrderGoodsMapper.insert2(wxMarketOrderGoods);
            }

            if (wxOrderSubmitBO.getUserCouponId() != 0 && wxOrderSubmitBO.getUserCouponId() != -1) {
                MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(wxOrderSubmitBO.getUserCouponId());
                marketCouponUser.setUsedTime(new Date());
                marketCouponUser.setOrderId(wxMarketOrder.getId());
                marketCouponUser.setUpdateTime(new Date());
                marketCouponUser.setDeleted(true);
                marketCouponUser.setStatus(((short) 1));
                marketCouponUserMapper.updateByPrimaryKey(marketCouponUser);
            }

            WxOrderSubmitVO wxOrderSubmitVO = new WxOrderSubmitVO();
            wxOrderSubmitVO.setGrouponLinkId(0);
            wxOrderSubmitVO.setOrderId(wxMarketOrder.getId());
            return wxOrderSubmitVO;

        }

        // cartId 不为0时 ---> 直接下单
        WxMarketCart marketCart = marketCartMapper.selectByPrimaryKey2(wxOrderSubmitBO.getCartId());
        BigDecimal goodsPrice = marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber()));
        wxMarketOrder.setGoodsPrice(goodsPrice);

        // 设置购物车cart状态
        marketCart.setDeleted(true);
        marketCart.setDeleted(false);
        marketCartMapper.updateByPrimaryKey2(marketCart);


        // 运输费用
        // 查询system表
        MarketSystem freightMin = marketSystemMapper.selectByPrimaryKey(6);
        MarketSystem freightValue = marketSystemMapper.selectByPrimaryKey(8);
        if (goodsPrice.intValue() >= Integer.parseInt(freightMin.getKeyValue())) {
            wxMarketOrder.setFreightPrice(BigDecimal.valueOf(0));
        } else {
            wxMarketOrder.setFreightPrice(BigDecimal.valueOf(Integer.parseInt(freightValue.getKeyValue())));
            // wxMarketOrder.setFreightPrice(BigDecimal.valueOf(10));
        }


        // 优惠券减免
        if (wxOrderSubmitBO.getCouponId() < 0 ) {
            // 不使用优惠券
            // wxMarketOrder.setFreightPrice(BigDecimal.valueOf(0));
            wxMarketOrder.setCouponPrice(BigDecimal.valueOf(0));
        } else if (wxOrderSubmitBO.getCouponId() > 0){
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmitBO.getCouponId());
            // 满足使用条件
            wxMarketOrder.setCouponPrice(marketCoupon.getDiscount());
        } else {

            // 默认使用金额最大的优惠券
            // 若couponId为0，查询该用户所有可用优惠券,找到面额最大的优惠券使用
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            marketCouponUserExample.createCriteria()
                    .andUserIdEqualTo(userId);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            // 遍历查询优惠券使用状态，如果没有使用，则选择优惠券金额最大的一张
            int discountMax = 0;
            for (MarketCouponUser marketCouponUser : marketCouponUsers) {
                // 判断是否使用
                if (marketCouponUser.getStatus() == 0) {
                    Integer couponId = marketCouponUser.getCouponId();
                    MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
                    // 选择优惠券金额最大的一张，需要判断条件
                    if (goodsPrice.intValue() > marketCoupon.getMin().intValue()) {
                        // 如果满足了最低金额，则代表可以使用优惠券
                        if (marketCoupon.getDiscount().intValue() >= discountMax ) {
                            discountMax = marketCoupon.getDiscount().intValue();
                        }
                    }
                }
            }
            wxMarketOrder.setCouponPrice(BigDecimal.valueOf(discountMax));

        }
        double orderPrice = wxMarketOrder.getGoodsPrice().doubleValue() + wxMarketOrder.getFreightPrice().doubleValue() - wxMarketOrder.getCouponPrice().doubleValue();
        wxMarketOrder.setOrderPrice(BigDecimal.valueOf(orderPrice));

        wxMarketOrder.setActualPrice(BigDecimal.valueOf(orderPrice));

        wxMarketOrder.setAddTime(new Date());
        wxMarketOrder.setUpdateTime(new Date());
        wxMarketOrder.setIntegralPrice(BigDecimal.valueOf(0));
        wxMarketOrder.setGrouponPrice(BigDecimal.valueOf(0));
        // wxMarketOrder.setComments(((short) 1));
        marketOrderMapper.insert2(wxMarketOrder);

        // 新增market order goods表的记录
        WxMarketOrderGoods wxMarketOrderGoods = new WxMarketOrderGoods();
        wxMarketOrderGoods.setOrderId(wxMarketOrder.getId());
        wxMarketOrderGoods.setGoodsId(marketCart.getGoodsId());
        wxMarketOrderGoods.setGoodsName(marketCart.getGoodsName());
        wxMarketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
        wxMarketOrderGoods.setProductId(marketCart.getProductId());
        wxMarketOrderGoods.setPrice(marketCart.getPrice());
        wxMarketOrderGoods.setNumber(marketCart.getNumber().shortValue());
        wxMarketOrderGoods.setSpecifications(marketCart.getSpecifications());
        wxMarketOrderGoods.setPicUrl(marketCart.getPicUrl());
        wxMarketOrderGoods.setAddTime(new Date());
        wxMarketOrderGoods.setUpdateTime(new Date());
        // wxMarketOrderGoods.setComment(-2);

        marketOrderGoodsMapper.insert2(wxMarketOrderGoods);


        if (wxOrderSubmitBO.getUserCouponId() != 0 && wxOrderSubmitBO.getUserCouponId() != -1) {
            MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(wxOrderSubmitBO.getUserCouponId());
            marketCouponUser.setUsedTime(new Date());
            marketCouponUser.setOrderId(wxMarketOrder.getId());
            marketCouponUser.setUpdateTime(new Date());
            marketCouponUser.setDeleted(true);
            marketCouponUser.setStatus(((short) 1));
            marketCouponUserMapper.updateByPrimaryKey(marketCouponUser);
        }

        WxOrderSubmitVO wxOrderSubmitVO = new WxOrderSubmitVO();
        wxOrderSubmitVO.setGrouponLinkId(0);
        wxOrderSubmitVO.setOrderId(wxMarketOrder.getId());
        return wxOrderSubmitVO;
    }

    /**
     * lxc 根据userid将状态为已发货（301）的订单查出来
     * @param status
     * @return
     */
    @Override
    public List<MarketOrder> queryOrderByStatus(int status) {

        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        criteria.andOrderStatusEqualTo((short)status);
        List<MarketOrder> orders = marketOrderMapper.selectByExample(marketOrderExample);

        return orders;
    }

    /**
     * lxc 系统自动确认收货 根据商品表id将订单状态从301修改到402
     * @param id
     */
    @Override
    public void modifyOrderStatusByOrderId(Integer id) {

        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short)402);
        marketOrder.setId(id);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public WxUserIndexVO selectOrderIndex(String username) {
        MarketUser marketUser = marketUserMapper.queryByUsername(username);
        Integer id = marketUser.getId();
        // 101待付款 201待发货 301待收货
        WxUserIndexVO wxUserIndexVO = new WxUserIndexVO();
        WxUserIndexOrderVO order = new WxUserIndexOrderVO();
        order.setUnpaid(marketOrderMapper.selectOrderStatus(101,id));
        order.setUnship(marketOrderMapper.selectOrderStatus(201,id));
        order.setUnrecv(marketOrderMapper.selectOrderStatus(301,id));
        if (marketOrderMapper.selectComments(id) == null){
            order.setUncomment(0);
        }else {
            order.setUncomment(marketOrderMapper.selectComments(id));
        }
        //order.setUncomment(marketOrderGoodsMapper.selectOrderStatus(0));
        wxUserIndexVO.setOrder(order);
        return wxUserIndexVO;
    }
}
